package com.rockcent.helper;

import com.alibaba.fastjson.JSON;
import com.rockcent.common.utils.HttpClientUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by marco on 2017/8/3.
 */
public enum WxAppHelper {

    SINGLETON;

    //访问页面
    private final static String PAGEAPI = "https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage?access_token=";

    private final Logger log = LoggerFactory.getLogger(WxAppHelper.class);

    /**
     * 获取accessToken
     * @param appId
     * @param appSecret
     * @return
     */
    public String getAccessToken(String appId, String appSecret) {
        String accessToken = null;
        log.info("getAccessToken appId:{},appSecret:{}",appId,appSecret);
        try {
            String result = HttpClientUtils.SINGLETON.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret);
            Map mapTypes = JSON.parseObject(result);
            accessToken = (String) mapTypes.get("access_token");
            log.info("getAccessToken access_token:{}" , accessToken);
        } catch (Exception e) {
            log.info("getAccessToken error message:{}",e.getMessage());
        }
        return accessToken;
    }

    /**
     * 小程序访问页面的统计数据
     * @param appId
     * @param appSecret
     * @param beginDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public String getweAnalysis(String appId,String appSecret, String beginDate, String endDate) throws Exception {
        String result = null;
        try {
            log.info("getAccessToken appId:{},appSecret:{},beginDate:{},endDate:{}",appId,appSecret,beginDate,endDate);
            String url = PAGEAPI+getAccessToken(appId,appSecret);
            HttpPost httpPost = new HttpPost(url);
            String json = "{\"begin_date\":\"" + beginDate + "\",\"end_date\":\"" + endDate + "\"}";
            log.info("getweAnalysis json:{}", json);
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            log.info("getweAnalysis error message:{}",e.getMessage());
        }
        return result;
    }
}
